package com.audition.thread.day02.code;

import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author xukang
 * @date 2021-03-12 11:28
 */
public class CachedData {
    Object data;
    private boolean cacheValid;
    final ReentrantReadWriteLock rwl = new ReentrantReadWriteLock();

    void processCachedData() {
        rwl.readLock().lock();
        if (!cacheValid) {
            //在获取写锁之前必须释放读锁
            rwl.readLock().unlock();
            rwl.writeLock().lock();
            //这里必须要判断数据的有效性,因为在释放读锁和获取写锁的空袭之间,可能有其他线程系修改了数据
            try {
                if (!cacheValid) {

                    data = new Object();
                    cacheValid = true;

                }
                //在不释放写锁的情况下 直接获取读锁 这就是读写锁的降级
                rwl.readLock().lock();
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                //释放了写锁 但依然拥有读锁
                rwl.writeLock().unlock();
            }


        }
        try {
            System.out.println(data);
        } finally {
            //释放读锁
            rwl.readLock().unlock();
        }
    }



}
